package com.example.xiaomiao.Service.Impl;

import com.example.xiaomiao.BO.PromptBO;
import com.example.xiaomiao.DO.Money_Record;
import com.example.xiaomiao.DTO.GetMoneyRequestDTO;
import com.example.xiaomiao.Mapper.MoneyRecordMapper;
import com.example.xiaomiao.Service.AIService;
import com.example.xiaomiao.Util.AIUtil;
import io.reactivex.rxjava3.core.Flowable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import static com.example.xiaomiao.Util.MyConstants.*;

@Service
public class AIServiceImpl implements AIService {
    @Resource
    MoneyRecordMapper moneyRecordMapper;
    @Resource
    AIUtil aiUtil;
    private static final Logger logger = LoggerFactory.getLogger(AIServiceImpl.class);

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Flowable<String> analysis(int userId, GetMoneyRequestDTO getMoneyRequestData) {
        LocalDate startDate = getMoneyRequestData.getStart_date();
        LocalDate endDate = getMoneyRequestData.getEnd_date();
        int start = getMoneyRequestData.getStart_index();
        int count = getMoneyRequestData.getCount();
        int total = moneyRecordMapper.getMoneyRecordNum(userId,startDate,endDate);
        List<Money_Record> moneyRecords = moneyRecordMapper.getMoneyRecords(userId,startDate,endDate,start,Math.min(count,total-start));
        if (moneyRecords.isEmpty())
            return Flowable.just("该时间段没有收支记录");;
        List<String> userMessages = new ArrayList<>();
        StringBuilder userMessage = new StringBuilder(String.format(USER_PROMPT,startDate.toString(),endDate.toString()));
        for(Money_Record moneyRecord : moneyRecords)
            userMessage.append(moneyRecord.getDate()).append(":").append(moneyRecord.getMoney()).append("元\n");
        userMessage.append(USER_PROMPT1);
        userMessages.add(userMessage.toString());
        List<String> systemMessages = new ArrayList<>();
        systemMessages.add(SYSTEM_PROMPT);
        PromptBO prompt = new PromptBO(userMessages,systemMessages);
        return aiUtil.getAnswerSSE(prompt);
    }
}
